<template>
  <div>
    <el-button type="primary" round @click="statusMeasure">开始测量</el-button>
    <el-button type="primary" round @click="removeMeasure">清除测量</el-button>
    <el-button type="primary" round @click="getshiduDatainfo">获取湿度</el-button>
    <!-- <el-button type="success" plain @click="loadData()">获取路径</el-button> -->
    <div id="map"></div>
    <div class="block" style="padding:0 40px ; margin-top: -10Vh;">
    <el-slider
      v-model="value"
      :step="step"
      :marks="marks"
      show-stops
     :max=92
     :format-tooltip="geshiweizi"
     @input="inputchange()"
     >
    </el-slider>
  </div>
    <poper ref="typhoonifo" :infodata="data"></poper>
  </div>
</template>

<script>

import "ol/ol.css";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { getVideoDetail,getshiduData } from "../api/taifeng.js";
import axios from 'axios'
import { Vector as VectorLayer, Image as imageLayers } from 'ol/layer';
import { Vector as VectorSource,Cluster } from 'ol/source';
import Static from 'ol/source/ImageStatic';
import Feature from 'ol/Feature';
import { Point, MultiLineString, LineString, Polygon } from 'ol/geom';
import { Style, Circle, Fill, Circle as CircleStyle, Stroke,Text } from 'ol/style';
import poper from '../components/popuer';
import featureObj from '../components/js/feature.js';
import Overlay from 'ol/Overlay';
import Draw from 'ol/interaction/Draw';
import { getLength } from 'ol/sphere';
import { unByKey } from 'ol/Observable';
import {getleidaData} from '../api/leida.js'
export default {
  data() {
    return {
      map: null,
      taifengjuanxy: null,
      isChangeSize: null,
      overlay: null,
      data: null,
      vector: null,
      measureTooltip: [],
      helpTooltip: [],
      pathArr:[],
      TimeAee:[],
     leidaLength:0,
     imageLayers:null,
     value: 4,
     step:4,
     marks: {
         
          
        }
    };
  },
  components: {
    poper,
  },
  async mounted() {
    // const data=getdaifengdata()
    // console.log(data)
    this.viewMap();
    this.loadData();
    this.desidnHoveOnmap();
    this.designClickMap();
    this.addOverlay();
    await this.getleidaData();
     this.drawPirMap(this,0);
    this.sclodData()
  },
  methods: {
    viewMap() {
      this.map = new Map({
        target: "map",
        layers: [
          // 天地图路网
          new TileLayer({
            source: new XYZ({
              url: 'http://t4.tianditu.com/DataServer?T=vec_w&X={x}&Y={y}&L={z}&tk=e33bff145f017205e949052045b56087'
            })
          }),

        ],
        view: new View({
          projection: "EPSG:4326",  //坐标系，即地球坐标系——WGS84：常见于 GPS 设备，Google 地图等国际标准的坐标体系。
          center: [123.3972282409668, 24.90960456049752],  //中心点坐标，即北京天安门
          zoom: 6
        })
      });
    },

    async loadData() {
      const { data } = await getVideoDetail();
      let points = data.data[0].points;
      let index = 0
      let source = new VectorSource()
      let layer = new VectorLayer()

      let drawlogo = setInterval(() => {
        if (index == points.length) {
          clearInterval(drawlogo)
          return;
        }

        //获取坐标点
        let position = [points[index].lng, points[index].lat]
        //绘制点要素
        let featurePoint = new Feature(new Point(position));
        featurePoint.set('typepoint', 'true')
        featurePoint.set('point', points[index])
        //设置点要素的样式
        featurePoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: this.selectFindColor(points[index].strong)
              }),
              radius: 4
            })
          }))
        source.addFeature(featurePoint)
        //绘制线要素
        if (index > 0) {
          let nextpoint = [points[index - 1].lng, points[index - 1].lat]
          let featureLine = new Feature(new LineString([position, nextpoint]))
          featureLine.set('typepline', 'true')
          source.addFeature(featureLine);
        }
        //绘制外面台风圈
        let taifengjuanxy = this.taifengjuanxy
        // // let feeaturePolygon=new Feature(new Polygon([taifengjuanxy]))
        if (taifengjuanxy !== null) {
          source.removeFeature(this.taifengjuanxy)
        }

        this.taifengjuanxy = this.drawSoider(points[index])
        source.addFeature(this.taifengjuanxy)
        index++

      }, 1000);
      layer.setSource(source);
      this.map.addLayer(layer)
      //数据格式


    },

    drawSoider(point) {
      var Configs = {
        CIRCLE_CENTER_X: parseFloat(point.lng),
        CIRCLE_CENTER_Y: parseFloat(point.lat),
        // CIRCLE_CENTER_X: point.lng,
        // CIRCLE_CENTER_Y: point.lat,
        CIRCLE_R: {
          "SE": 0.5,
          "NE": 0.3,
          "NW": 0.2,
          "SW": 0.5
        }
      };
      let positions = []
      var wkt0 = "", _interval = 6;
      for (var i = 0; i < 360 / _interval; i++) {
        var _r = 0;
        var _ang = i * _interval;
        if (_ang > 0 && _ang <= 90) {
          _r = Configs.CIRCLE_R.NE;
        }
        else if (_ang > 90 && _ang <= 180) {
          _r = Configs.CIRCLE_R.NW;
        }
        else if (_ang > 180 && _ang <= 270) {
          _r = Configs.CIRCLE_R.SW;
        }
        else {
          _r = Configs.CIRCLE_R.SE;
        }

        var x = Configs.CIRCLE_CENTER_X + _r * Math.cos(_ang * 3.14 / 180);
        var y = Configs.CIRCLE_CENTER_Y + _r * Math.sin(_ang * 3.14 / 180);
        positions.push([x, y])
      }

      let feeaturePolygon = new Feature(new Polygon([positions]))
      return feeaturePolygon;

    },
    // 注册鼠标经过事件
    desidnHoveOnmap() {
      let _this = this;
      //pointermove为鼠标移动事件
      this.map.on('pointermove', (ev) => {
        let pixel = ev.pixel;     //坐标点
        let feature = _this.map.forEachFeatureAtPixel(pixel, (feature) => { return feature })
        //判断元素纯在
        if (feature) {
          let name = featureObj.typeHudge(feature) + 'Move'
          featureObj[name].apply(_this, [feature])
          //判断为点元素
        }
        else {
          _this.huifuSize();
          this.map.getTargetElement().style.cursor = ''
          this.overlay.setPosition(undefined)
        }
      })
    },
    huifuSize() {
      let _this = this
      if (_this.isChangeSize !== null) {
        _this.isChangeSize.getStyle().getImage().setRadius(4)
        _this.isChangeSize.changed()
      }
    },
    //点击事件
    designClickMap() {
      let _this = this
      this.map.on('click', function (ev) {
        console.log(ev.pixel)
        let pixel = ev.pixel;
        let feature = _this.map.forEachFeatureAtPixel(pixel, (feature) => { return feature })

        if (feature) {
          let name = featureObj.typeHudge(feature) + 'Click'
          featureObj[name].apply(_this, [feature])

        }
      })
    },
    addOverlay() {
      const overlay = new Overlay({
        element: this.$refs.typhoonifo.$el,
        aotuPan: true,
        autoPanAnimation: {
          duration: 250,
        },

      });
      this.overlay = overlay
      overlay.setPosition(undefined)
      this.map.addOverlay(overlay)
    },

    setoverlatposition(point) {
      this.overlay.setPosition(point)
    },
    //测量距离
    statusMeasure() {
      const source = new VectorSource();
      this.vector = new VectorLayer({
        source: source,
        style: {
          'fill-color': 'rgba(255, 255, 255)',
          'stroke-color': '#ff0000',
          'stroke-width': 3,
          'circle-radius': 7,
          'circle-fill-color': '#00ffff',
        },
      });
      let helpTooltipElement;
      let helpTooltip;
      let feature;
      let _this = this;
      let measureTooltipElement;
      let measureTooltip;
      let listener;
      let draw
      
      const pointerMoveHandler = function (evt) {
        if (evt.dragging) {
          return;
        }
        /** @type {string} */
        let helpMsg = '点击开始';
        if (feature) {
          helpMsg = '双击结束';
        }
        helpTooltipElement.innerHTML = helpMsg;
        helpTooltip.setPosition(evt.coordinate);
        _this.helpTooltip.push(helpTooltip)
        helpTooltipElement.classList.remove('hidden');
      };

      //建立提示框
      function createHelpTooltip() {
        if (helpTooltipElement) {
          helpTooltipElement.parentNode.removeChild(helpTooltipElement);
        }
        helpTooltipElement = document.createElement('div');
        helpTooltipElement.className = 'ol-tooltip hidden';
        helpTooltip = new Overlay({
          element: helpTooltipElement,
          offset: [15, 0],
          positioning: 'center-left',
        });
        _this.map.addOverlay(helpTooltip);
      }
      createHelpTooltip()

      // 绘画对象
      addInteraction()
      function addInteraction() {

        draw = new Draw({
          source: source,
          type: 'LineString',
          style: new Style({
            fill: new Fill({
              color: 'rgba(0, 5, 255, 0.5)',
            }),
            stroke: new Stroke({
              color: 'rgba(2, 5, 255, 0.8)',
              lineDash: [10, 10],
              width: 2,
            }),
            image: new CircleStyle({
              radius: 10,
              stroke: new Stroke({
                color: 'rgba(255, 5, 2, 0.8)',
              }),
              fill: new Fill({
                color: 'rgba(255, 5, 2, 0.8)',
              }),
            }),
          }),
        });

        _this.map.addInteraction(draw);
        _this.map.addLayer(_this.vector)
      }
      //结果提示
      function createMeasureTooltip() {
        if (measureTooltipElement) {
          measureTooltipElement.parentNode.removeChild(measureTooltipElement);
        }
        measureTooltipElement = document.createElement('div');
        measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
        measureTooltip = new Overlay({
          element: measureTooltipElement,
          offset: [0, -15],
          positioning: 'bottom-center',
          stopEvent: false,
          insertFirst: false,
        });
        _this.map.addOverlay(measureTooltip);
      }

      draw.on('drawstart', function (evt) {
        // set sketch
        feature = evt.feature;
        /** @type {import("../src/ol/coordinate.js").Coordinate|undefined} */
        let tooltipCoord = evt.coordinate;
        listener = feature.getGeometry().on('change', function (evt) {
          const geom = evt.target;
          let output;
          output = formatLength(geom) || " ";
          tooltipCoord = geom.getLastCoordinate();
          measureTooltipElement.innerHTML = output;
          measureTooltip.setPosition(tooltipCoord);
          _this.measureTooltip.push(measureTooltip)
        });
      });
      draw.on('drawend', function () {
        measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
        measureTooltip.setOffset([0, -7]);
        // unset sketch
        feature = null;
        // unset tooltip so that a new one can be created
        measureTooltipElement = null;
        helpTooltip.setPosition(undefined)
        createMeasureTooltip();
        unByKey(listener);
        unByKey(mapmove);
        _this.map.removeInteraction(draw);
      });


      const formatLength = function (line) {
        const length = getLength(line) * 111194;
        let output;
        if (length > 100) {
          output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
        } else {
          output = Math.round(length * 100) / 100 + ' ' + 'm';
        }
        return output;
      };
      //鼠标移动s事件
      const mapmove = this.map.on('pointermove', pointerMoveHandler);
      createMeasureTooltip()
    },
    removeMeasure() {
      let _this = this
      this.map.removeLayer(this.vector)

      _this.measureTooltip.map(item => {
        item.setPosition(undefined)
      })

      _this.helpTooltip.map(item => {
        console.log(item)
        item.setPosition(undefined)
      })
    },
    //获取雷达数据
    async getleidaData(){
   const {data}=await getleidaData()
   let image=new imageLayers()
   this.imageLayers=image;
   this.map.addLayer(this.imageLayers);
   let value=data.data.value;
      let timearr=[];
      let patharr=[];
 
for(let i = value.length-1;i>=0;i--){
  let timelength=value[i].time.length;
 
  for(let j=timelength-1;j>=0;j--){
    let curTime=value[i].time[j]
    let TimeEnd=curTime.slice(0,2)+':'+curTime.slice(2,)
    timearr.push(TimeEnd);
    patharr.push(value[i].path[j])

  }
this.pathArr=patharr;
this.TimeAee=timearr;
}
this.leidaLength=timearr.length;


    },
    //绘制雷达图像
    drawPirMap({imageLayers},index){
    let leftBottom=[110.3819558585585,20.768156744];
   let rightTop=[12.607568215662,30.6514788214];
   let extent=leftBottom.concat(rightTop)
   let source=new Static({
    imageExtent: extent,
    url:'image/'+this.pathArr[index],
   })
   imageLayers.setSource(source);
   imageLayers.changed()
    },
    //滑块滑动事件
    inputchange(){
     let index=this.value/this.step
     this.drawPirMap(this,index)
    },
    // 处理滑动条数据
    sclodData(){ 
   let step=Math.floor(100/this.leidaLength)
   let index=this.value/this.step
   //处理marks
  let marks={};
  let leng=this.leidaLength;
  let time=this.TimeAee
  
  this.step=step
  for(let i=0;i<leng;i++){
  marks[i*step]=time[i]
  }
  
  this.marks=marks
  },
  geshiweizi(value){
    let index=value/this.step
  let date=new Date();
  let month=date.getMonth()+1;
  let day=date.getDate()
  return month+'-' +day+ '   '+ this.TimeAee[index]
  },
  //获取湿度数据
  async getshiduDatainfo(){
    const {data}=await getshiduData();
    const shidudata=data.data.data;
    const length=shidudata.length;
   const _this=this
    const features = new Array(length)
  
    for (let i = 0; i < length; ++i) {
  const coordinates = [parseInt(shidudata[i].x), parseInt(shidudata[i].y)];
  features[i] = new Feature(new Point(coordinates));
  features[i].set('value',shidudata[i].v)
}
    const source = new VectorSource({
        features: features,
});

const clusterSource = new Cluster({
  distance: parseInt(50, 10),
  // minDistance: parseInt(minDistanceInput.value, 10),
  source: source,
});
const styleCache = {};
const clusters = new VectorLayer({
  source: clusterSource,
  style: function (feature) {
 
  //  console.log(feature.values_.features[0].values_.value)
   let text=feature.values_.features[0].values_.value
   let color=_this.getcolor(text)
    const size = feature.get('features').length;
    let style = styleCache[size];
    if (!style) {
      style = new Style({
        image: new CircleStyle({
          radius: 10,
          stroke: new Stroke({
            color: '#fff',
          }),
          fill: new Fill({
            color: color,
          }),
        }),
        text: new Text({
          text: text+'%',
          fill: new Fill({
            color: '#fff',
          }),
        }),
      });
      styleCache[size] = style;
    }
    return style;
  },
});
 this.map.addLayer(clusters)
  },
  //处理颜色
  getcolor(num){
    if(num>90) return '#125364'
    else if(num>80) return '#856289'
    else if(num>70) return '#856959'
    else if(num>60) return '#781635'
    else if(num>50) return '#5136aa'
    else if(num>40) return '#4123ff'
    else if(num>30) return '#456813'
    else if(num>20) return '#41aa55'
    else if(num>10) return '#aabbcc'
    else if(num>8) return '#ddeeff'
  },
    /**
     *  @param {String} windleave 台风等级描述
     * @return {String} map[winleave] 对应的颜色
     * 
     */
    selectFindColor(windleave) {
      let map = {
        "热带风暴": 'red',
        '热带低压': 'blue',
        '强热带风暴': 'green',
        '台风': 'orange',
        '强台风': 'yellow',
        '超强台风': 'salmon'
      }
      return map[windleave]
    }
  }
};
</script>

<style lang="css" >
 #map {
        width: 1600px;
        height: 600px;
        z-index: 1;
      }
      .ol-tooltip {
        position: relative;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        color: white;
        padding: 4px 8px;
        opacity: 0.7;
        white-space: nowrap;
        font-size: 12px;
        cursor: default;
        user-select: none;
      }
      .ol-tooltip-measure {
        opacity: 1;
        font-weight: bold;
      }
      .ol-tooltip-static {
        background-color: #ffcc33;
        color: black;
        border: 1px solid white;
      }
      .ol-tooltip-measure:before,
      .ol-tooltip-static:before {
        border-top: 6px solid rgba(0, 0, 0, 0.5);
        border-right: 6px solid transparent;
        border-left: 6px solid transparent;
        content: "";
        position: absolute;
        bottom: -6px;
        margin-left: -7px;
        left: 50%;
      }
      .ol-tooltip-static:before {
        border-top-color: #ffcc33;
      }
</style>
